// 开启express服务
const express = require("express");
const app = express();
const server = require("http").Server(app);

app.set("views", "./views"); // 设置模板存放路径
app.set("view engine", "ejs"); // express设置使用ejs模板
app.use(express.static("public")); // 设置静态资源服务路径
app.use(express.urlencoded({ extended: true }));

const rooms = {};

// 开启socket服务
const io = require("socket.io")(server);

app.get("/", (req, res) => {
  res.render("index", { rooms: rooms });
});

app.get("/:room", (req, res) => {
  if (rooms[req.params.room] === null) {
    res, redirect("/");
  }

  res.render("room", { roomName: req.params.room });
});

app.post("/room", (req, res) => {
  // 判断房间是否已经存在
  if (rooms[req.body.room]) {
    return res.redirect("/");
  }

  rooms[req.body.room] = { users: {} };
  res.redirect(req.body.room);

  io.emit("room-create", req.body.room);
});

// 创建socketio链接
io.on("connection", (socket) => {
  // 监听客户端发送过来的new-user类的消息
  socket.on("new-user", (room, name) => {
    rooms[room].users[socket.id] = name;
    socket.join(room);
    socket.to(room).emit("user-connected", name);
  });

  // 监听客户端发送过来的send-chat-message类的消息
  socket.on("send-chat-message", (room, message) => {
    socket.to(room).emit("chat-message", {
      message: message,
      name: rooms[room].users[socket.id],
    });
  });

  // 监听客户端断开disconnect的链接
  socket.on("disconnect", () => {
    getUserRooms(socket).forEach((room) => {
      socket.to(room).emit("user-disconnected", rooms[room].users[socket.id]);
      delete rooms[room].users[socket.id];
    });
  });
});

function getUserRooms(socket) {
  return Object.entries(rooms).reduce((names, [name, room]) => {
    if (room.users[socket.id]) names.push(name);
    return names;
  }, []);
}

server.listen(3000);
